package com.ruoyi.oss.service.abstractd;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.oss.entity.UploadResult;
import com.ruoyi.oss.properties.OSSProperties;
import com.ruoyi.oss.service.IOssStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

/**
 * @author 最爱喝兽奶
 * @create 2022/6/13
 **/
public abstract class AbstractOssStrategy implements IOssStrategy {

    protected final Logger logger = LoggerFactory.getLogger(AbstractOssStrategy.class);

    protected OSSProperties ossProperties;

    public abstract void init(OSSProperties ossProperties);

    @Override
    public abstract void createBucket();

    @Override
    public abstract String getServiceType();

    /**
     * 传入文件前缀和文件后缀，生成文件在minio中的路径
     *
     * @param prefix 可以为空
     * @param suffix 不能为空
     * @return
     */
    public String getPath(String prefix, String suffix) {
        String uuid = UUID.randomUUID().toString();
        String path = DateUtils.datePath() + "/" + uuid;
        if (StringUtils.isNoneBlank(prefix)) {
            path = prefix + path;
        }
        return path + suffix;
    }

    /**
     * 上传自定义路径的
     * @param data 文件
     * @param path 文件在minio中的路径
     * @param contentType http类型
     * @return
     */
    @Override
    public abstract UploadResult upload(byte[] data, String path, String contentType);

    @Override
    public UploadResult upload(InputStream is, String path, String contentType) {
        // 将文件输入流中的数据
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        byte[] flush = new byte[1024];
        int len = -1;
        try {
            while ((len = is.read(flush)) != -1) {
                bao.write(flush, 0, len);
            }
            bao.flush();
        } catch (Exception e) {
            logger.error("文件传输失败", e);
        }
        return upload(bao.toByteArray(), path, contentType);
    }

    @Override
    public abstract UploadResult uploadSuffix(byte[] data, String suffix, String contentType);

    @Override
    public abstract UploadResult uploadSuffix(InputStream is, String suffix, String contentType);

    /**
     *整个文件url的前缀
     * @return
     */
    public String getEndpointLink() {
        return ossProperties.getEndpoint() + "/" + ossProperties.getBucketName();
    }
}